package dao

import (
	"context"
	"inventory/internal/constant"
	"inventory/pkg/ecode"
	"time"

	"inventory/internal/model"
)

// FindPurchaseOrders 获取仓库下采购单列表
func (d *Dao) FindPurchaseOrders(ctx context.Context, sgID, warehouseID uint32, startDate, endDate time.Time,
	pageNo, pageSize int, queryOrderNumber string) (total int64, orders []*model.PurchaseOrder, err error) {
	db := d.TransContext(ctx).Model(&model.PurchaseOrder{}).Where(
		"sg_id = ? and create_time between ? and ?  and status = ? and warehouse_id = ?",
		sgID, startDate, endDate.Add(time.Hour*24-time.Second), constant.PurchaseOrderDone, warehouseID)
	if queryOrderNumber != "" {
		if len(queryOrderNumber) < 4 {
			err = ecode.BadRequest("单号模糊搜索至少需要4位数字")
		}
		db = db.Where("order_number like ?", "%"+queryOrderNumber+"%")
	}
	if err = db.Count(&total).Error; err != nil {
		err = d.processSqlError(err)
		return
	}
	err = db.Order("id desc").Offset((pageNo - 1) * pageSize).Limit(pageSize).Find(&orders).Error
	if err != nil {
		err = d.processSqlError(err)
	}
	return
}

// GetPurchaseOrder 获取采购单
func (d *Dao) GetPurchaseOrder(ctx context.Context, sgID uint32, orderNumber string) (purchase *model.PurchaseOrder, err error) {
	purchase = &model.PurchaseOrder{}
	err = d.TransContext(ctx).Model(&model.PurchaseOrder{}).Where("sg_id = ? and order_number = ?", sgID, orderNumber).Take(&purchase).Error
	if err != nil {
		err = d.processSqlError(err)
	}
	return
}

// FindPurchaseOrderDetails 获取采购详情
func (d *Dao) FindPurchaseOrderDetails(ctx context.Context, orderID uint64) (details []*model.PurchaseDetail, err error) {
	err = d.TransContext(ctx).Model(&model.PurchaseDetail{}).Where("order_id = ?", orderID).Find(&details).Error
	if err != nil {
		err = d.processSqlError(err)
	}
	return
}
